package com.hqyj.listener;

import com.hqyj.dao.OrderInfoMapper;
import com.hqyj.dao.ShopMapper;
import com.hqyj.pojo.OrderInfo;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 项目:rabbitmq-230301-summer
 * 描述:
 * 时间:2023/8/7 9:31
 * 作者:admin
 * 版本:1.0
 **/
@Component
@Slf4j
public class ShopListener {

      @Resource
      OrderInfoMapper orderInfoMapper;

      @Resource
       ShopMapper shopMapper;
      @RabbitListener(queues = "shopQueue")
      @Transactional
      public void kill(Channel channel, Message message, Map<String,Object> map) throws IOException {
            log.info("用户{}开始消费商品{}",map.get("userName"),map.get("shopName"));
            //创建订单对象
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrderName(map.get("shopName")+"");
            orderInfo.setOrderNum(1);
            orderInfo.setOrderUser(map.get("userName")+"");
            orderInfo.setOrderCreateTime(new Date());
            //插入
            int num = orderInfoMapper.insert(orderInfo);
            if(num>0){
                //库存
                int n =shopMapper.updateStock(map.get("shopName")+"");
                if(n>0){

                    try {
                        //确认消费成功
                        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

                    } catch (IOException e) {
                        e.printStackTrace();
                        //判断消息是否是重新投递
                        if(message.getMessageProperties().isRedelivered()){
                            //拒绝消费
                            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                            log.info("拒绝消费，消息插入到数据库中");
                        }else{
                            //消息消费确认失败
                            try {
                                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                            } catch (IOException ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                }

            }



      }



}
